package com.dream.service.user.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.response.BaseListResponse;
import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.common.model.response.ListModel;
import com.dream.service.general.domain.enums.StatusCode;
import com.dream.service.user.api.UserAddrService;
import com.dream.service.user.config.UserAddrConfig;
import com.dream.service.user.dao.StoreAddrDao;
import com.dream.service.user.dao.UserAddrDao;
import com.dream.service.user.domain.model.CountryModel;
import com.dream.service.user.domain.model.StoreAddrModel;
import com.dream.service.user.domain.model.UserAddrModel;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kangd on 2016/3/24.
 */
public class UserAddrServiceImpl implements UserAddrService {

//    private Map<String,String> country_sn=new  HashMap<String,String>();


    private UserAddrDao userAddrDao;

    private StoreAddrDao storeAddrDao;

    private org.slf4j.Logger logger = LoggerFactory.getLogger(UserAddrServiceImpl.class);

    public UserAddrDao getUserAddrDao() {
        return userAddrDao;
    }

    @Autowired
    public void setUserAddrDao(UserAddrDao userAddrDao) {
        this.userAddrDao = userAddrDao;
    }

    public StoreAddrDao getStoreAddrDao() {
        return storeAddrDao;
    }

    @Autowired
    public void setStoreAddrDao(StoreAddrDao storeAddrDao) {
        this.storeAddrDao = storeAddrDao;
    }

    private void init(){
//        List<CountryModel> countryModels=null;
//        try {
//            countryModels =userAddrDao.selectCountry(null,null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("国家初始化失败");
//        }
//        for(CountryModel c: countryModels){
//            country_sn.put(c.getCountry_name_en().toLowerCase(),c.getCountry_name_sn());
//        }
//        System.out.println(JSONObject.toJSON(country_sn));
    }

    /**
     * 增加收货地址
     * @param userAddrModel
     * @return
     */
    @Override  @Transactional
    public BaseResponse<UserAddrModel> addUserAddress(UserAddrModel userAddrModel) throws Exception {
        long startTime = System.currentTimeMillis();
        if(userAddrModel == null || StringUtils.isEmpty(userAddrModel.getPin()) || StringUtils.isEmpty(userAddrModel.getCity()) ||
                StringUtils.isEmpty(userAddrModel.getDetail_address1()) ||
                StringUtils.isEmpty(userAddrModel.getName()))
        {
            BaseResponse baseResponse= new BaseResponse<UserAddrModel>(ErrorCode.PARAM_ERROR);
            return baseResponse;
        }
        if(userAddrModel.getIsDefault()==null){
            userAddrModel.setIsDefault(1);
        }

        BaseResponse<UserAddrModel> baseResponse= new BaseResponse<UserAddrModel>();
        try{
            String storeId = userAddrModel.getStoreId();
            if(!StringUtils.isEmpty(storeId)){
                try {
                    StoreAddrModel storeAddrModel = storeAddrDao.selectById(Integer.parseInt(storeId));
                    if (storeAddrModel != null && !StringUtils.isEmpty(storeAddrModel.getName())) {
                        userAddrModel.setStoreName(storeAddrModel.getName());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            logger.info("add user addr:{}",JSONObject.toJSONString(userAddrModel));
            UserAddrModel userAddrModelDefault = userAddrDao.selectByPINDefault(userAddrModel.getPin());
            if(userAddrModelDefault != null){
                // 先把原来默认地址换成非默认
                if(userAddrModel.getIsDefault().equals(UserAddrConfig.DEFAULT_ADDR_ID)) {
                    System.out.println("先把原来默认地址换成非默认");
                    userAddrModelDefault.setIsDefault(0);
                    userAddrDao.updateUserAddr(userAddrModelDefault);
                }
            }
//            else {
//                System.out.println("没有默认地址，必须上传为默认地址");
//                // 没有默认地址，必须上传为默认地址
//                if( ! userAddrModel.getIsDefault().equals(UserAddrConfig.DEFAULT_ADDR_ID)) {
//                    userAddrModel.setIsDefault(UserAddrConfig.DEFAULT_ADDR_ID);
//                }
//            }
            userAddrDao.addUserAddr(userAddrModel);

            baseResponse.packData(true, ErrorCode.OK.getCode(), "", null, userAddrModel);
        }catch (Throwable e){
            e.printStackTrace();
            baseResponse.packData(false, ErrorCode.DB_ERROR.getCode(), "", null, null);
        }
        baseResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseResponse;
    }

    /**
     * 修改用户详细收货地址
     * @param userAddrModel
     * @return
     */
    @Override  @Transactional
    public BaseResponse<UserAddrModel> modifyUserAddress(UserAddrModel userAddrModel) throws Exception {
        long startTime = System.currentTimeMillis();
        if(userAddrModel == null  ||
                StringUtils.isEmpty(userAddrModel.getPin()) ||
                StringUtils.isEmpty(userAddrModel.getCountry()) || StringUtils.isEmpty(userAddrModel.getCity()) ||
                StringUtils.isEmpty(userAddrModel.getDetail_address1()) ||
                StringUtils.isEmpty(userAddrModel.getName()))
        {
            BaseResponse baseResponse= new BaseResponse<UserAddrModel>(ErrorCode.PARAM_ERROR);
            return baseResponse;
        }
        BaseResponse<UserAddrModel> baseResponse= new BaseResponse<UserAddrModel>();


        try {
            UserAddrModel userAddrModelDefault = userAddrDao.selectByPINDefault(userAddrModel.getPin());
            if(userAddrModelDefault != null){
                // 先把原来默认地址换成非默认
                if( userAddrModel.getIsDefault().equals(UserAddrConfig.DEFAULT_ADDR_ID)) {
                    if(userAddrModelDefault.getReceiving_id() != userAddrModel.getReceiving_id()){
                        userAddrModelDefault.setIsDefault(0);
                        logger.info("update default user addr:{}",JSONObject.toJSONString(userAddrModelDefault));
                        userAddrDao.updateUserAddr(userAddrModelDefault);
                    }
                }else {
                    if(userAddrModelDefault.getReceiving_id() == userAddrModel.getReceiving_id()){
                        userAddrModel.setIsDefault(UserAddrConfig.DEFAULT_ADDR_ID);
                    }
                }
            }else {
                // 没有默认地址，必须上传为默认地址    这个逻辑走不到
                if( ! userAddrModel.getIsDefault().equals(UserAddrConfig.DEFAULT_ADDR_ID)) {
                    userAddrModel.setIsDefault(UserAddrConfig.DEFAULT_ADDR_ID);
                }
            }
            logger.info("update user addr:{}",JSONObject.toJSONString(userAddrModel));
            userAddrDao.updateUserAddr(userAddrModel);
            baseResponse.packData(true, ErrorCode.OK.getCode(), "", null, userAddrModel);
        }catch (Exception e){
            e.printStackTrace();
            baseResponse.packData(false , ErrorCode.DB_ERROR.getCode(), "", null, null);
        }

        baseResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseResponse;
    }

    /**
     * 修改为默认地址
     * @param pin
     * @param userAddressID
     * @return
     */
    @Override @Transactional
    public BaseResponse<Boolean> modifyUserDefaultAddr(String pin, int userAddressID) throws Exception {
        long startTime = System.currentTimeMillis();
        logger.info("modifyUserDefaultAddr user addr:{},userAddressId:{}",pin,userAddressID);
        if(StringUtils.isEmpty(pin) || userAddressID ==0 ){
            BaseResponse baseResponse= new BaseResponse<Boolean>(ErrorCode.PARAM_ERROR);
            return baseResponse;
        }

        UserAddrModel userAddrModelDefault = userAddrDao.selectByPINDefault(pin);
        if(userAddrModelDefault!=null && userAddrModelDefault.getReceiving_id()!=userAddressID){
            // 先把原来默认地址换成非默认
            userAddrModelDefault.setIsDefault(0);
            userAddrDao.updateUserAddr(userAddrModelDefault);
        }
        int i = userAddrDao.updateUserDefaultAddr(pin,Integer.valueOf(userAddressID));
        if(i != 1){
            throw new RuntimeException(ErrorCode.NOT_EXIST.getError_msg());
        }
        BaseResponse<Boolean> baseResponse= new BaseResponse<Boolean>();
        baseResponse.packData(true, ErrorCode.OK.getCode(), "", null, true);
        baseResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseResponse;
    }

    /**
     * 删除用户地址
     * @param pin
     * @param userAddressID 用户地址id
     * @return
     */
    @Override
    public BaseResponse<Boolean> delUserAddress(String pin, int userAddressID) {
        long startTime = System.currentTimeMillis();
        if(StringUtils.isEmpty(pin)|| userAddressID ==0 ){
            BaseResponse baseResponse= new BaseResponse<Boolean>(ErrorCode.PARAM_ERROR);
            return baseResponse;
        }

        BaseResponse<Boolean> baseResponse= new BaseResponse<Boolean>();
        try {
//            int i=userAddrDao.deleteUserAddrModel(pin, userAddressID);
            UserAddrModel model = new UserAddrModel();
            model.setReceiving_id(userAddressID);
            model.setStatus_code(StatusCode.DISABLE.getStatus_code());
            int i = userAddrDao.updateUserAddr(model);
            if(i==1){
                baseResponse.packData(true, ErrorCode.OK.getCode(), "", null, true);
            }else{
                UserAddrModel userAddrModel = userAddrDao.selectByReceivingID(pin, userAddressID);
                if(userAddrModel != null && userAddrModel.getIsDefault() == 1){
                    baseResponse.packData(false, ErrorCode.NOT_AUTH.getCode(), "Cannot Remove Default Address", null, false);
                }else {
                    baseResponse.packData(false, ErrorCode.NOT_EXIST.getCode(), "pin or userAddrID not exist", null, false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseResponse;
    }

    /**
     * 获取用户地址列表
     * @param pin
     * @return
     */
    @Override
    public BaseListResponse getUserAddressList(String pin) {
        long startTime = System.currentTimeMillis();
        if(StringUtils.isEmpty(pin)){
            BaseListResponse baseListResponse= new BaseListResponse(ErrorCode.PARAM_ERROR);
            return baseListResponse;
        }
        BaseListResponse baseListResponse= new BaseListResponse();
        List<UserAddrModel> userAddrModelList;
        try {
            userAddrModelList=userAddrDao.selectByPIN(pin);
            ListModel<List<UserAddrModel>> listModel = new ListModel<List<UserAddrModel>>();
            listModel.setList(userAddrModelList);
            // 用户最多可以设置 20 个地址
            listModel.setAmount(UserAddrConfig.MAX_USERADDR);
            baseListResponse.packData(true, ErrorCode.OK.getCode(), "", null, listModel);
        } catch (Exception e) {
            e.printStackTrace();
            baseListResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseListResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseListResponse;
    }

    /**
     * 获取用户默认地址
     * @param pin
     * @return
     */
    @Override
    public BaseResponse<UserAddrModel> getUserDefaultAddress(String pin) {
        long startTime = System.currentTimeMillis();
        if(StringUtils.isEmpty(pin)){
            BaseResponse baseResponse= new BaseResponse<UserAddrModel>(ErrorCode.PARAM_ERROR);
            return baseResponse;
        }
        BaseResponse<UserAddrModel> baseResponse= new BaseResponse<UserAddrModel>();
        try {
            UserAddrModel userAddrModel = userAddrDao.selectByPINDefault(pin);
            baseResponse.packData(true, ErrorCode.OK.getCode(), "", null, userAddrModel);
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseResponse;
    }

    /**
     * 获取用户地址
     *
     * @param pin
     * @param userAddressID
     * @return
     */
    @Override
    public BaseResponse<UserAddrModel> getUserAddress(String pin, int userAddressID) {
        long startTime = System.currentTimeMillis();
        if(StringUtils.isEmpty(pin)|| userAddressID ==0 ){
            BaseResponse baseResponse= new BaseResponse<Boolean>(ErrorCode.PARAM_ERROR);
            return baseResponse;
        }
        BaseResponse<UserAddrModel> baseResponse= new BaseResponse<UserAddrModel>();
        try {
            UserAddrModel userAddrModel = userAddrDao.selectByReceivingID(pin,userAddressID);
            baseResponse.packData(true, ErrorCode.OK.getCode(), "", null, userAddrModel);
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseResponse;
    }

    /**
     * 获取国家列表
     *
     * @return
     */
    @Override
    public BaseListResponse getCountry() {
        long startTime = System.currentTimeMillis();
        BaseListResponse baseListResponse= new BaseListResponse();
        ListModel listModel = new ListModel();
        try {
            // 这里默认查询配送地址的国家
            Integer scope_type = 0;
            List<CountryModel> countryModelListFreq =userAddrDao.selectCountry(UserAddrConfig.FREQ_COUNTRY,scope_type);
            listModel.setAmount(countryModelListFreq.size());
            List<CountryModel> countryModelList =userAddrDao.selectCountry(null,scope_type);
            countryModelListFreq.addAll(countryModelList);
            listModel.setList(countryModelListFreq);
            baseListResponse.packData(true, ErrorCode.OK.getCode(), "", null, listModel);
        } catch (Exception e) {
            e.printStackTrace();
            baseListResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseListResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseListResponse;
    }
}
